package easy;

public class Solution_938 {

    private int sum = 0;

    public int rangeSumBST(TreeNode root, int low, int high) {
        sum = 0;
        dps(root, low, high);
        return sum;
    }

    private void dps(TreeNode node, int low, int high) {
        if (node == null) {
            return;
        }
        if (node.val >= low) {
            dps(node.left, low, high);
        }
        if (low <= node.val && node.val <= high) {
            sum += node.val;
        }
        if (node.val <= high) {
            dps(node.right, low, high);
        }
    }

    public static void main(String[] args) {
        Solution_938 model = new Solution_938();
        /*TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(7);
        root.right = new TreeNode(15);
        root.right.right = new TreeNode(18);*/
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.left.left = new TreeNode(3);
        root.left.left.left = new TreeNode(1);
        root.left.right = new TreeNode(7);
        root.left.right.left = new TreeNode(6);
        root.right = new TreeNode(15);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(18);
        System.out.println(model.rangeSumBST(root, 6, 10));
    }

    static class TreeNode {

        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
